package wildlife;

import java.sql.*;
import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
class SaveImageToDatabase {
 void insert(File f) throws SQLException {
	HttpServletRequest request=ServletActionContext.getRequest();
	HttpSession session=request.getSession();
// declare a connection by using Connection interface 
Connection connection = null;
/* Create string of connection url within specified format with machine 
name, port number and database name. Here machine name id localhost 
and database name is mahendra. */
String connectionURL = "jdbc:mysql://localhost:3306/image";
/*declare a resultSet that works as a table resulted by execute a specified 
sql query. */
ResultSet rs = null;
// Declare prepare statement.
PreparedStatement psmnt = null;
// declare FileInputStream object to store binary stream of given image.
FileInputStream fis;
try {
// Load JDBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
String username=session.getAttribute("username").toString();
/* Create a connection by using getConnection() method that takes 
parameters of string type connection url, user name and password to 
connect to database. */
connection = DriverManager.getConnection(connectionURL, "root", "adithri");
// create a file object for image by specifying full path of image as parameter.
//File image = new File("../images/"+session.getAttribute("username").toString()+".jpg");
/* prepareStatement() is used for create statement object that is 
used for sending sql statements to the specified database. */
Statement st=connection.createStatement();
fis = new FileInputStream(f);
Connect c=new Connect();
ResultSet rs1=c.getResult("select * from image where username='"+username+"'");

psmnt = connection.prepareStatement("insert into image(image,username) values(?,'"+username+"')");
	psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
	//psmnt.executeUpdate();
	
//else {psmnt = connection.prepareStatement("insert into saveimage values(?,?)");}


//psmnt.setBinaryStream(1, (InputStream)fis, (int)(image.length()));
//psmnt.setString(2,session.getAttribute("username").toString());
/* executeUpdate() method execute specified sql query. Here this query 
insert data and image from specified address. */ 
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("unsucessfull to upload image.");
}
}
// catch if found any exception during rum time.
catch (Exception ex) {
System.out.println("Found some error : "+ex);
}
finally {
// close all the connections.
connection.close();
psmnt.close();
}
}
}
